/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * framre2.java
 *
 * Created on 2009-01-08, 01:11:03
 */

package DBBrowser;

//import java.awt.TrayIcon;

import DBBrowser_pack.DBLogin;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;
import javax.swing.event.*;


/**
 *
 * @author Dom
 */
public class DataFrame extends javax.swing.JFrame {

    /** Creates new form framre2 */
    public DataFrame() {
        initComponents();
jTable1.setModel(model);
nr=jTable1.getRowCount();
model.addTableModelListener(new TableModelListener(){
            public void tableChanged(TableModelEvent e) {

                if(jTable1.getSelectedRows().length!=0)
                   //   System.out.println("TEST");
                if(e.getType()==0) aktualizuj();
              
            //   throw new UnsupportedOperationException("Not supported yet.");
            }

});
}






    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPopupMenu1 = new javax.swing.JPopupMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        jMenuItem2 = new javax.swing.JMenuItem();
        jMenuItem3 = new javax.swing.JMenuItem();
        jMenuItem4 = new javax.swing.JMenuItem();
        jMenuItem5 = new javax.swing.JMenuItem();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();

        jMenuItem1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/DBBrowser/cancel_16.png"))); // NOI18N
        jMenuItem1.setText("Usuń");
        jMenuItem1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jMenuItem1MouseClicked(evt);
            }
        });
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });
        jPopupMenu1.add(jMenuItem1);

        jMenuItem2.setText("Cofnij zmiany");
        jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem2ActionPerformed(evt);
            }
        });
        jPopupMenu1.add(jMenuItem2);

        jMenuItem3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/DBBrowser/add_16.png"))); // NOI18N
        jMenuItem3.setText("Nowy wiersz");
        jMenuItem3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem3ActionPerformed(evt);
            }
        });
        jPopupMenu1.add(jMenuItem3);

        jMenuItem4.setText("Wyślij");
        jMenuItem4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem4ActionPerformed(evt);
            }
        });
        jPopupMenu1.add(jMenuItem4);

        jMenuItem5.setText("Odśwież");
        jMenuItem5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem5ActionPerformed(evt);
            }
        });
        jPopupMenu1.add(jMenuItem5);

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        jScrollPane1.setAutoscrolls(true);

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jTable1.setColumnSelectionAllowed(true);
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);
        jTable1.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/DBBrowser/accepted_48.png"))); // NOI18N
        jButton1.setText("Wyslij");
        jButton1.setToolTipText("Wyślij uaktualnienie danych do bazy");
        jButton1.setBorder(null);
        jButton1.setBorderPainted(false);
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/DBBrowser/add_48.png"))); // NOI18N
        jButton2.setText("Nowy wiersz");
        jButton2.setToolTipText("Dodaj nowy wiersz do tabeli");
        jButton2.setBorder(null);
        jButton2.setBorderPainted(false);
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/DBBrowser/refresh_48.png"))); // NOI18N
        jButton3.setText("Odśwież");
        jButton3.setToolTipText("Odśwież");
        jButton3.setBorder(null);
        jButton3.setBorderPainted(false);
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 442, Short.MAX_VALUE)
                        .addGap(15, 15, 15))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap())))
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jButton1, jButton2, jButton3});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2)
                    .addComponent(jButton3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 234, Short.MAX_VALUE)
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {jButton1, jButton2, jButton3});

        pack();
    }// </editor-fold>//GEN-END:initComponents
//List <int> ve=new List();
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed

wyslij();
        // TODO add your handling code here:
    }//GEN-LAST:event_jButton1ActionPerformed
    private void aktualizuj() {
        if(flag==false)
nr=jTable1.getRowCount();

        if(jTable1.getSelectedRow()<nr){
   int x=jTable1.getSelectedRow();
String[] g=new String[jTable1.getColumnCount()];
for(int i=0;i<jTable1.getColumnCount();i++)
    g[i]=jTable1.getValueAt(x, i).toString();
        v.add(g);        // TODO add your handling code here:
        for(int i=0;i<g.length;i++)
        System.out.printf(g[i]+", ");
            }
    }
    private void wyslij(){
      if(flag==false)
       nr=model.getRowCount();
           String[] c=new String[model.getColumnCount()];
    for(int j=0;j<model.getColumnCount();j++)
        c[j]=model.getColumnName(j);
      /*
        s=new String[model.getRowCount()][model.getColumnCount()];
        String[] c=new String[model.getColumnCount()];
        for(int i=0;i<nr;i++){
    for(int j=0;j<model.getColumnCount();j++){
        c[j]=model.getColumnName(j);
        s[i][j]=model.getValueAt(i, j).toString();
      }
    DBLogin.getManager().update(this.getTitle(),c, s[i]);
   }*/
        String[] g=new String[model.getColumnCount()];
        String z="";
        if(flag==true)
        for(int i=nr;i<model.getRowCount();i++){
            z="";
    for(int j=0;j<model.getColumnCount();j++){
      g[j]=model.getValueAt(i, j).toString();
    z+="\'"+g[j]+"\'";
    if(j<model.getColumnCount()-1)
        z+=", ";
    }

    DBLogin.getManager().QueryAsk("insert into "+this.getTitle()+" values("+z+")");
  }

                for(int i=0;i<v.size();i++)
             for(int j=0;j<v.get(i).length;j++)
                     DBLogin.getManager().update(this.getTitle(),c, v.get(i));
  DBLogin.getManager().QueryAsk("commit");
  DBLogin.getManager().QueryAsk("end transaction");
  flag=false;

 
       /*
        //  for(int i=0;i<v.size();i++)
        //      for(int j=0;j<v.get(i).length;j++)
        //             DBLogin.getManager().update(this.getTitle(),c, v.get(i));
        DBLogin.getManager().update(this.getTitle(),c, s[i]);
        // }
        }

        String[] g=new String[model.getColumnCount()];
        String z="";
        if(flag==true)
        for(int i=nr;i<model.getRowCount();i++){
        z="";
        for(int j=0;j<model.getColumnCount();j++){
        g[j]=model.getValueAt(i, j).toString();
        z+="\'"+g[j]+"\'";
        if(j<model.getColumnCount()-1)
        z+=", ";
        }

        DBLogin.getManager().QueryAsk("insert into "+this.getTitle()+" values("+z+")");
        }
        DBLogin.getManager().QueryAsk("commit");
        DBLogin.getManager().QueryAsk("end transaction");
        flag=false;
        }*/
}
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
    String s[]=new String[model.getColumnCount()];
     if(flag==false)
    nr=model.getRowCount();
  flag=true;
  for(int i=0;i<s.length;i++)
        s[i]="";
    if(model.getRowCount()==0)
         model.addRow(s);
    else if(model.getValueAt(model.getRowCount()-1,0).toString().isEmpty()==false)
        model.addRow(s);
  
//     TODO add your handling code here:
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
DBLogin.getManager().QueryAsk("begin transaction");
        if(evt.getButton()==3){
   
  //  jPopupMenu1.validate();
    //jScrollPane1.add(jPopupMenu1);
   // jPopupMenu1.setLocation(this.getSize().width/2, this.getSize().height/2);
    jScrollPane1.add(jPopupMenu1);
jPopupMenu1.show(jTable1, evt.getX(), evt.getY());
}
        // TODO add your handling code here:
    }//GEN-LAST:event_jTable1MouseClicked

    private void jMenuItem1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jMenuItem1MouseClicked

// TODO add your handling code here:
    }//GEN-LAST:event_jMenuItem1MouseClicked

    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
    // javax.swing.JOptionPane.showMessageDialog(null, "xxxxx");
        String ss="";
        if(jTable1.getSelectedRowCount()!=0){
        int wiersz[]=jTable1.getSelectedRows();
for(int i=0;i<wiersz.length;i++){
        ss=model.getValueAt(wiersz[i], 0).toString();
    DBLogin.getManager().QueryAsk("delete from "+this.getTitle()+" where "+model.getColumnName(0)+" = "+ss); 
model.removeRow(wiersz[i]);
}
jTable1.repaint();
        }
        // TODO add your handling code here:
    }//GEN-LAST:event_jMenuItem1ActionPerformed

    private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed
     DBLogin.getManager().QueryAsk("rollback"); 
refresh();
     // TODO add your handling code here:
    }//GEN-LAST:event_jMenuItem2ActionPerformed

    private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem3ActionPerformed
       String s[]=new String[model.getColumnCount()];
     if(flag==false)
    nr=model.getRowCount();
    for(int i=0;i<s.length;i++)
        s[i]="";
    if(model.getRowCount()==0)
         model.addRow(s);
    else if(model.getValueAt(model.getRowCount()-1,0).toString().isEmpty()==false)
        model.addRow(s);
  flag=true;
        // TODO add your handling code here:
    }//GEN-LAST:event_jMenuItem3ActionPerformed

    private void jMenuItem4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem4ActionPerformed
wyslij();
        // TODO add your handling code here:
    }//GEN-LAST:event_jMenuItem4ActionPerformed
private void refresh(){
         model.setDataVector(DBLogin.getManager().QueryTable(this.getTitle()),DBLogin.getManager().columnNames(""));
     jTable1.repaint();
}
    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
  refresh();
        // TODO add your handling code here:
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jMenuItem5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem5ActionPerformed
refresh();
// TODO add your handling code here:
    }//GEN-LAST:event_jMenuItem5ActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
wyslij();        // TODO add your handling code here:
    }//GEN-LAST:event_formWindowClosing

    @Override
protected void finalize(){
DBLogin.getManager().QueryAsk("commit");
DBLogin.getManager().QueryAsk("end transaction");
    }
    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new DataFrame().setVisible(true);
            }
        });
    }
    boolean flag=false;
    int nr=0;
    String s[][];
    javax.swing.event.TableModelEvent menusel;
protected javax.swing.table.DefaultTableModel model= new javax.swing.table.DefaultTableModel();
private java.util.Vector  <String[]>  v=new java.util.Vector();
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JMenuItem jMenuItem3;
    private javax.swing.JMenuItem jMenuItem4;
    private javax.swing.JMenuItem jMenuItem5;
    private javax.swing.JPopupMenu jPopupMenu1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    // End of variables declaration//GEN-END:variables

}
